<!--
 * @Author: 一路向阳 tt_sunzhenfeng@163.com
 * @Date: 2024-05-31 21:43:41
 * @LastEditors: 一路向阳 tt_sunzhenfeng@163.com
 * @LastEditTime: 2024-06-03 22:09:54
 * @FilePath: \vue3_upload_file\vue3_upload_demo\src\pages\Upload\index.vue
 * @Description: 这是默认设置,请设置`customMade`, 打开koroFileHeader查看配置 进行设置: https://github.com/OBKoro1/koro1FileHeader/wiki/%E9%85%8D%E7%BD%AE
-->
<template>
  <div class="one-page-container">
    <el-form :model="form" label-suffix="：" label-position="left">
      <el-form-item label="文件名称">
        <el-input v-model="form.name" />
      </el-form-item>

      <el-form-item label="文件上传">
        <!-- 覆盖默认行为 -->
        <el-upload class="upload-demo" v-model:file-list="files" :limit="1" :http-request="handleCustomUpload"
          :on-exceed="handleUploadExceed" :on-remove="handleRemoveFile">
          <el-button type="primary">上传文件</el-button>
          <template #tip>
            <div class="el-upload__tip">
              jpg/png files with a size less than 500KB.
            </div>
          </template>
        </el-upload>
      </el-form-item>

      <el-form-item>
        <el-button type="primary" @click="handleUploadSubmit">选择确认上传</el-button>
      </el-form-item>
    </el-form>
  </div>
</template>

<script setup>
import { ref, reactive } from 'vue';
import { useRouter } from 'vue-router';

import { uploadFile } from '@/api/upload';
import { toast } from '@/utils/common';

const router = useRouter();

// 表单数据
const form = reactive({
  name: '',
  file: []
});

// 上传文件列表
const files = ref([]);

const handleResetData = data => {
  for (const key in data) {
    form[key] = data?.[key];
  }
}

// 覆盖默认行为
const handleCustomUpload = data => {
  const { file } = data;
  form.file = file;
}

// 个数限制
const handleUploadExceed = () => {
  toast('超出上传数量限制', 'warning')
}

// 移除图片
const handleRemoveFile = file => {
  form.file = form.file.filter(item => item.uid !== file.uid);
}

// 提交
const handleUploadSubmit = async () => {
  const formData = new FormData();
  for (const key in form) {
    if (form?.[key]) {
      formData.append(key, form?.[key]);
    }
  }
  const { success, msg } = await uploadFile(formData).finally(() => handleResetData({ name: '', file: [] }));
  if (success) {
    files.value = [];
    toast(msg, 'success');
    router.push('/source');
  }
}
</script>

<style lang="less" scoped>
.one-page-container {
  width: 100%;
  height: 100%;
  @apply p-10;
}
</style>